package singleThreaded;

import java.io.IOException;

import javax.swing.JOptionPane;

import MultiThreaded.PageAnalyzer;
/**
 * MainSingle class. This class initializes the main fields to be used in the single threaded.
 * @author zsyed
 *
 */
public class MainSingle {
	/** 
	 * The number of URLs the user wishes to crawl.
	 */
	private final int my_crawl_limit;
	
	/** 
	 * The initial input URL.
	 */
	private String my_starting_url;
	
	/** 
	 * A string containing the keywords.
	 */
	private final String my_keywords; 
	
	/**
	 * output of the entire process.
	 */
	private String my_output; 
	
	/**
	 * constructor.
	 * @param the_max_pages the limited number of page crawl.
	 * @param the_url the starting url inputting by the user.
	 * @param the_keywords the key word inputting by the user.
	 */
	public MainSingle(int the_max_pages, String the_url, String the_keywords) {
		my_crawl_limit = the_max_pages;
		my_starting_url = the_url; 
		my_keywords = the_keywords;
	}
	/**
	 * Crawl the url from starting url. Stop when it reaches the max pages crawl or 
	 * stop when it run out of url.
	 */
	public void Crawl() {
		//check if the url is valid.
		if (!my_starting_url.startsWith("http://")) {
			my_starting_url = "http://"+ my_starting_url;
		}
		if (my_crawl_limit > 0 && isURL(my_starting_url)) {
			PageRetriever retriever = new PageRetriever(my_crawl_limit);
			try {
				retriever.crawlPages(my_starting_url);
			} catch (IOException e) {//this should never happen.
				e.printStackTrace();
			}
			PageAnalyzerSingle analyze = new PageAnalyzerSingle(retriever.getCurrentParser(), retriever.getURLs());
			analyze.initializeKeyword(my_keywords);
			my_output = analyze.getAnalyzingData().toString();
		} else {
			JOptionPane.showMessageDialog(null, "Invalid url at:" + my_starting_url);
		}
	}
	/**
	 * Get the output of the entire crawling process.
	 */
	public String getOutPut() {
		return my_output;
	}
	/**
	 * Get my starting url.
	 */
	public String getStartingURL() {
		return my_starting_url;
	}
	
	/** 
	 * helper class to check the validity of a url using url patterns matching 
	 */
	private boolean isURL(String url)
	{
	 //Assigning the url format regular expression
	 String urlPattern="^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*";
	 return url.matches(urlPattern); 
	}
}
